package com.buric.auth.service.impl;

import com.buric.api.dto.admin.LoginAdmin;
import com.buric.api.service.admin.AdminApiService;
import com.buric.auth.service.AuthAdminService;
import com.buric.auth.service.CommonService;
import com.buric.auth.service.data.in.LoginInData;
import com.buric.common.constant.ContextConstants;
import com.buric.common.constant.MemberKey;
import com.buric.common.exception.ServiceException;
import com.buric.common.sevice.RedisService;
import com.buric.common.util.SecurityUtils;
import com.buric.common.utils.JwtUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: zhou.wei
 * @description 认证业务实现
 * @date: 2024/5/10 16:44
 */
@Service
public class AuthAdminServiceImpl implements AuthAdminService {

    @Resource
    private AdminApiService userApiService;

    @Resource
    private RedisService redisService;
    @Override
    public LoginAdmin login(LoginInData inData) {


        LoginAdmin loginUser = userApiService.getUserByUsername(inData.getUsername()).getData();
        if(loginUser == null){
            throw new ServiceException("账号或密码错误！");
        }
        boolean b = SecurityUtils.matchesPassword(inData.getPassword(), loginUser.getPassword());
        if(!b){
            throw new ServiceException("密码错误！");
        }
        Map<String,Object> loginMap = new HashMap<>();
        loginMap.put(ContextConstants.USER_NAME,loginUser.getUsername());
        loginMap.put(ContextConstants.USER_ID, loginUser.getId());
        String token = JwtUtils.createToken(loginMap);
        loginUser.setToken(token);
        redisService.setCacheObject(MemberKey.MEMBER_TOKEN_KEY + token, loginUser.getId(), 7L, TimeUnit.DAYS);
        return loginUser;
    }
}
